﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MyOCR.Translate
{
    class TengXun_TranslateHandle: TranslateHandle
    {
        static TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        Int64 currentTime = Convert.ToInt64(ts.TotalSeconds);
        public override string GetResult()
        {
            var lst = new List<string>();
            var content = GetJson();
            dynamic json = JsonConvert.DeserializeObject(content);

            try
            {
                return string.Join("\r\n", json.Response.TargetText.ToString());
            }
            catch (Exception)
            {
                return "错误码 ：" + json.errorCode + ",请检查密钥或网络状态";
            }
        }

        protected override string GetJson()
        {
            var client = new RestClient("https://tmt.tencentcloudapi.com/");
            var request = new RestRequest(Method.POST);
            request.AddHeader("host", "tmt.tencentcloudapi.com");
            request.AddParameter("Action", "TextTranslate");//
            request.AddParameter("Version", "2018-03-21");
            request.AddParameter("Region", "ap-guangzhou");//
            request.AddParameter("Timestamp", currentTime);//
            request.AddParameter("Nonce", "1223455");//
            request.AddParameter("SecretId", Program._config.TengXun_Secret_Id);//

            request.AddParameter("Signature", getSign());
            request.AddParameter("SourceText", need_Tslt);//
            request.AddParameter("Source", "auto");//
            request.AddParameter("Target", "zh");//
            request.AddParameter("ProjectId", "0");//

            IRestResponse response = client.Execute(request);

            return response.Content;
        }

        protected override string getSign()
        {
            string sign = string.Format("POSTtmt.tencentcloudapi.com/?Action={0}&Nonce={1}&ProjectId={2}" +
                "&Region={3}&SecretId={4}&Source={5}&SourceText={6}&Target={7}&Timestamp={8}&Version={9}", "TextTranslate",
                "1223455","0", "ap-guangzhou", Program._config.TengXun_Secret_Id, "auto", need_Tslt, "zh",currentTime, "2018-03-21");

            var enc = Encoding.UTF8;
            HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(Program._config.TengXun_Secret_Key));
            hmac.Initialize();

            byte[] buffer = enc.GetBytes(sign);
            return Convert.ToBase64String(hmac.ComputeHash(buffer));
        }
    }
}
